﻿namespace PlsPlaylist
{
    using PlaylistCopy.Contract;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.IO;
    using System.Text;

    [Export(typeof(IPlaylist))]
    public class PlsPlaylistImpl : IPlaylist
    {
        private readonly ILogger logger;

        [ImportingConstructor]
        public PlsPlaylistImpl([Import("Logger")] ILogger logger)
        {
            this.logger = logger;
        }

        public string PlaylistExtension
        {
            get { return "pls"; }
        }

        public IEnumerable<string> GetMusicFiles(Stream stream)
        {
            this.logger.Info("Started parsing PLS playlist...");

            using (var reader = new StreamReader(stream, Encoding.Default))
            {
                var line = reader.ReadLine();
                if (line == null || !line.ToLowerInvariant().Equals("[playlist]"))
                {
                    yield break;
                }

                line = reader.ReadLine();
                if (line == null)
                {
                    yield break;
                }

                while ((line = reader.ReadLine()) != null)
                {
                    if (!line.ToLowerInvariant().StartsWith("file"))
                    {
                        continue;
                    }

                    yield return line.Remove(0, line.IndexOf('=') + 1);
                }
            }
        }
    }
}
